iT邦幫忙

0

Redis 發佈訂閱消息對列實作(Python)

  • 分享至 

  • xImage
  •  
'''
Redis pubsub, subscribe, listen, json.loads
'''
# pip install redis
import redis
import json

r = redis.Redis(host="localhost", port=6379, db=1) # connect to redis

p = r.pubsub(ignore_subscribe_messages=True) # set pubsub to ignore_subscrible_messages true

p.subscribe('topic-1', 'topic-2') # subscrible a topic
p.psubscribe('topic-*') # or psubscrible, pattern mode  
for message in p.listen(): # listen what you just subscribed
    # message is a type of dict, including four keys , type, pattern, channel and data
    data = json.loads(message['data']) # extract data 
    print(type(data), data)

"""
Redis publish, json.dumps
"""
import redis
import json


db = redis.Redis(host="localhost", port=6379, db=1)
dict_data = {"name": "John", "gender": "male"}
json_data = json.dumps(dict_data)
db.publish("topic-1", json_data)

> {"name": "John", "gender": "male"}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言